<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Interactive Python</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="Python, interactive, programming, language, learn Python">
<meta name="description" content="In this chapter of the Python tutorial, we will
work with interactive Python interpreter.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<div class="content">

<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>


<h1>Interactive Python</h1>

<p>
In this part of the Python programming tutorial, we will talk about 
interactive Python interpreter. 
</p>

<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* NewSquare */
google_ad_slot = "0364418177";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script>  

<p>
Python code can be launched in two basic ways. As a script or 
inside an interactive interpreter. 
</p>

<pre class="code">
#!/usr/bin/python

# first.py

print "The Python tutorial"
</pre>

<p>
This is an example of a small Python script. It is launched 
from a UNIX shell. 
</p>

<pre>
$ ./first.py 
The Python tutorial
</pre>

<h2>Interactive interpreter</h2>

<p>
Another way of running Python code is the interactive Python interpreter. 
The Python interpreter is very useful for our explorations. When we quickly 
want to test some basic functionality of the Python language and we don't want to
write a whole script. To get the interactive interpreter, we execute the Python 
command on our favourite shell. 
</p>


<pre class="code">
$ python
Python 2.7.2+ (default, Jul 20 2012, 22:12:53) 
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 
</pre>

<p>
This is the welcome message of the Python interpreter. We see the version of Python 
on our machine. In our case it is Python 2.7.2. The ">>>" is the prompt used in the 
Python interactive mode. To leave the interpreter and 
return back to the shell, we can type Ctrl + D or <code>quit()</code>. 
Typing Ctrl + L will clear the screen of the Python interpreter. 
</p>

<p>
Now we can query for some useful information. 
</p>

<pre class="code">
>>> credits
    Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
    for supporting Python development.  See www.python.org for more information.
</pre>

<p>
If we type <code>credits</code> we get some information about organizations 
involved in Python development. 
</p>

<pre class="code">
>>> copyright
Copyright (c) 2001-2011 Python Software Foundation.
All Rights Reserved.

Copyright (c) 2000 BeOpen.com.
All Rights Reserved.

Copyright (c) 1995-2001 Corporation for National Research Initiatives.
All Rights Reserved.

Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
All Rights Reserved.
</pre>

<p>
The <code>copyright</code> command gives the copyright of the 
Python programming language. 
</p>

<p>
The <code>license()</code> command provides several pages regarding 
the license of Python. 
</p>


<h2>Getting help</h2>

<p>
The <code>help</code> command provides some help about Python. 
</p>

<pre class="code">
>>> help
Type help() for interactive help, or help(object) for help about object.
>>> 
</pre>

<p>
We can use the command in two ways. Either we can get some help about a specific 
object or we enter a interactive help
mode.
</p>

<p>
For example, if we type <code>help(True)</code>, we get some information about bool objects.
</p>

<pre class="code">
Help on bool object:

class bool(int)
 |  bool(x) -> bool
 |  
 |  Returns True when the argument x is true, False otherwise.
 |  The builtins True and False are the only two instances of the class bool.
 |  The class bool is a subclass of the class int, and cannot be subclassed.
 |  
 |  Method resolution order:
 |      bool
 |      int
 |      object
 |  
 |  Methods defined here:
 |  
 |  __and__(...)
 |      x.__and__(y) &lt;==&gt; x&amp;y

 ...
</pre>

<p>
If the topic is larger than one page, we can scroll it using the arrows. 
If we want to quit the topic, we press the q key. 
</p>

<p>
If we type <code>help()</code> we get the interactive help mode of the interpreter. 
</p>

<pre class="code">
>>> help()

Welcome to Python 2.7!  This is the online help utility.

If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://docs.python.org/tutorial/.

Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules.  To quit this help utility and
return to the interpreter, just type "quit".

To get a list of available modules, keywords, or topics, type "modules",
"keywords", or "topics".  Each module also comes with a one-line summary
of what it does; to list the modules whose summaries contain a given word
such as "spam", type "modules spam".

help> 
</pre>

<p>
To leave the help mode and return to the interpreter, we use 
the <code>quit</code> command. 
</p>

<hr class="btm">

<p>
The <code>keywords</code> command gives a list of available keywords in 
Python programming language.  
</p>

<pre class="code">
help> keywords

Here is a list of the Python keywords.  Enter any keyword to get more help.

and                 elif                if                  print
as                  else                import              raise
assert              except              in                  return
break               exec                is                  try
class               finally             lambda              while
continue            for                 not                 with
def                 from                or                  yield
del                 global              pass
</pre>

<p>

<p>
If we type any of the keywords, we get some help on it. 
</p>

<hr class="btm">

<p>
The <code>modules</code> command gives a list of available modules. 
Again, typing a name of the module will provide additional help.
</p>

<p>
Finally, we have the <code>topics</code> command. 
</p>

<pre class="code">
help> topics

Here is a list of available topics.  Enter any topic name to get more help.

ASSERTION           DEBUGGING           LITERALS            SEQUENCEMETHODS2
ASSIGNMENT          DELETION            LOOPING             SEQUENCES
ATTRIBUTEMETHODS    DICTIONARIES        MAPPINGMETHODS      SHIFTING
ATTRIBUTES          DICTIONARYLITERALS  MAPPINGS            SLICINGS
AUGMENTEDASSIGNMENT DYNAMICFEATURES     METHODS             SPECIALATTRIBUTES
BACKQUOTES          ELLIPSIS            MODULES             SPECIALIDENTIFIERS
BASICMETHODS        EXCEPTIONS          NAMESPACES          SPECIALMETHODS
BINARY              EXECUTION           NONE                STRINGMETHODS
BITWISE             EXPRESSIONS         NUMBERMETHODS       STRINGS
BOOLEAN             FILES               NUMBERS             SUBSCRIPTS
CALLABLEMETHODS     FLOAT               OBJECTS             TRACEBACKS
CALLS               FORMATTING          OPERATORS           TRUTHVALUE
CLASSES             FRAMEOBJECTS        PACKAGES            TUPLELITERALS
CODEOBJECTS         FRAMES              POWER               TUPLES
COERCIONS           FUNCTIONS           PRECEDENCE          TYPEOBJECTS
COMPARISON          IDENTIFIERS         PRINTING            TYPES
COMPLEX             IMPORTING           PRIVATENAMES        UNARY
CONDITIONAL         INTEGER             RETURNING           UNICODE
CONTEXTMANAGERS     LISTLITERALS        SCOPING             
CONVERSIONS         LISTS               SEQUENCEMETHODS1   
</pre>


<p>
The topics command gives a list of topics regarding Python programming language. 
Here we can find some useful information. 
</p>

<h2>Python Code</h2>

<p>
Now we will see the real benefit of the Python interpreter. 
</p>

<pre class="code">
>>> 2 + 4
6
>>> 5 * 56
280
>>> 5 - 45
-40
>>> 
</pre>

<p>
Python interpreter can be used as a calculator. Each expression is executed 
right away and the result is shown on the screen. 
</p>

<pre class="code">
>>> a = 3
>>> b = 4
>>> a**b
81
>>> a == b
False
>>> a &lt; b
True
>>>
</pre>

<p>
We can define variables and perform operations on them. 
</p>

<pre class="code">
>>> import random
>>> dir(random)
['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 
'SystemRandom', 'TWOPI', 'WichmannHill', '_BuiltinMethodType', '_MethodType',
'__all__', '__builtins__', '__doc__', '__file__', '__name__', '_acos', 
'_ceil', '_cos', '_e', '_exp', '_hexlify', '_inst', '_log', '_pi', '_random',
'_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 
'betavariate', 'choice', 'expovariate', 'gammavariate', 'gauss', 
'getrandbits', 'getstate', 'jumpahead', 'lognormvariate', 'normalvariate',
'paretovariate', 'randint', 'random', 'randrange', 'sample', 'seed',
'setstate', 'shuffle', 'uniform', 'vonmisesvariate', 'weibullvariate']
>>> 
</pre>

<p>
Here we imported a random module. With the <code>dir()</code> function, we further explore the
random module.  
</p>

<p>
With the help of the special <code>__doc__</code> string, we can get help on a specific function. 
</p>

<pre class="code">
>>> print random.seed.__doc__
Initialize internal state from hashable object.

        None or no argument seeds from current time or from an operating
        system specific randomness source if available.

        If a is not None or an int or long, hash(a) is used instead.
>>> 
</pre>

<p>
The <code>locals()</code> command shows our current local namespace. 
</p>

<pre class="code">
>>> locals()
{'__builtins__': &lt;module '__builtin__' (built-in)&gt;, '__name__': '__main__', 
'random': &lt;module 'random' from '/usr/lib/python2.5/random.pyc'&gt;, '__doc__': None}
</pre>

<p>
We can see the random module, that we have previously imported.
</p>

<pre class="code">
>>> class Car:
...   pass
... 
>>> def function():
...   pass
... 
>>> for i in range(5):
...   print i
... 
0
1
2
3
4
>>> 
</pre>

<p>
We can define our own classes, functions or use control flow structures. 
We must not forget to indent the code. To finish each of these blocks of 
code, we type enter key twice. 
</p>

<pre class="code">
>>> import os
>>> os.getcwd()
'/home/vronskij/programming/python'
>>> os.system('ls')
empty.pyc       fibonacci.pyc  ifyouwantme~  monica     old        perl.pl
ruby.rb         stopiter.py    tests         works
</pre>

<p>
Here we import the <code>os</code> module and interact with the operating system. 
</p>

<p>
Finally, we want to exit the interpreter. We can exit the interpreter in several ways:
</p>

<ul>
<li>Ctrl + D</li>
<li>quit()</li>
</ul>

<p>
We can also exit the interpreter programatically. 
</p>

<pre class="code">
>>> raise SystemExit
$ 
</pre>

<p>
or
</p>

<pre class="code">
>>> import sys
>>> sys.exit()
$
</pre>

<p>
The interpreter is exited.
</p>

<h2>The Zen of Python</h2>

<p>
The Zen of Python is a set of rules how to write good Python code.
It reflects somehow the philosophy of the language. 
</p>

<pre class="code">
>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
</pre>

<p>
The rules can be read by launching <code>import this</code>.
</p>


<p>
In this chapter we have looked at Python interactive interpreter. 
</p>


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡ 
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified December 17, 2012  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

